import {Component, signal} from '@angular/core';
import {Router, RouterModule} from '@angular/router';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {catchError, finalize, tap} from 'rxjs/operators';
import {throwError} from 'rxjs';

@Component({
  selector: 'app-login',
  imports: [ReactiveFormsModule, RouterModule],
  templateUrl: './login.html',
  styleUrl: './login.css'
})
export class Login {
  loginForm: FormGroup;
  error = signal('');
  loading = signal(false);

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private http: HttpClient
  ) {
    this.loginForm = this.fb.group({
      username: ['user', [Validators.required]],
      password: ['passwd', [Validators.required]]
    });
  }

  onSubmit() {
    if (this.loginForm.valid) {
      this.loading.set(true);
      this.error.set('');

      const {username, password} = this.loginForm.value;

      // 设置请求头
      const httpOptions = {
        headers: new HttpHeaders({
          'Content-Type': 'application/json'
        })
      };

      console.log('发送登录请求到: /api/login');

      // 向后端发送认证请求，使用相对路径
      this.http.post(`/api/login`, {username, password}, httpOptions)
        .pipe(
          tap((response: any) => {
            console.log('登录响应:', response);
            // 登录成功，保存token到localStorage
            if (response.data.token) {
              localStorage.setItem('token', response.data.token);
            }

            // 跳转到主页
            this.router.navigate(['/dashboard']);
          }),
          catchError(error => {
            console.error('登录错误:', error);
            // 处理认证错误
            if (error.status === 401) {
              this.error.set('用户名或密码错误');
            } else if (error.status === 0) {
              this.error.set('无法连接到服务器，请检查网络连接和后端服务');
            } else {
              this.error.set('登录失败，请稍后重试');
            }
            return throwError(() => error);
          }),
          finalize(() => {
            this.loading.set(false);
          })
        )
        .subscribe();
    }
  }
}
